package com.chenbei.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.common.exception.LogicHandleException;
import com.chenbei.erp.domain.Product;
import com.chenbei.erp.vo.req.ProductReq;
import com.chenbei.erp.mapper.ProductMapper;
import com.chenbei.erp.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@Slf4j
public class ProductService extends ServiceImpl<ProductMapper, Product> implements IProductService {

    private final Object lock = new Object();

    @Override
    public void add(Product product) {
        synchronized (lock) {
            LambdaQueryWrapper<Product> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Product::getName, product.getName())
                    .eq(Product::getCategoryId, product.getCategoryId())
                    .eq(Product::getUnitId, product.getUnitId());
            if (count(lambdaQueryWrapper) > 0) {
                throw new LogicHandleException("产品已存在");
            }

            long count = count();
            product.setCode("PD" + String.format("%04d", (count + 1)));
            save(product);
        }
    }

    @Override
    public void update(Product product) {
        LambdaQueryWrapper<Product> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Product::getId, product.getId())
                .eq(Product::getName, product.getName())
                .eq(Product::getCategoryId, product.getCategoryId())
                .eq(Product::getUnitId, product.getUnitId());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicHandleException("产品已存在");
        }
        updateById(product);
    }

    @Override
    public void delete(long id) {
        removeById(id);
    }

    @Override
    public Page<Product> pageList(ProductReq productQuery) {
        Page<Product> pageConfig = new Page<>(productQuery.getPageNum(), productQuery.getPageSize());
        return baseMapper.pageList(pageConfig, productQuery);
    }

    @Override
    public List<Product> list(ProductReq productQuery) {
        return baseMapper.list(productQuery);
    }
}
